<?php
/**
 * @author yuanyitian
 * @date 2023/7/7 2:18
 */

namespace api\admin;

use DOMDocument;
use DOMXPath;
use utils\base64_to_file;
use utils\oss;
use ZipArchive;

class user
{
    public function total($data)
    {
        $con = con();
        $sql = "SELECT 
                    type,
                     CASE type
                     WHEN 1 THEN '学术会员'
                     WHEN 2 THEN '观众'
                     WHEN 3 THEN '展商'
                     ELSE '其他'
                     END AS type_label,
                    COUNT(*) AS total
                    FROM user
                    GROUP BY type_label
                        ";
        $res = mysqli_query($con, $sql);
        $res = mysqli_fetch_all($res, true);
        mysqli_close($con);
        return out_right($res);

    }

    //获取用户统计分页列表
    public function list($data)
    {
        $page = (int)$data["page"];
        $size = (int)$data["size"];
        $name = $data["name"];
        $phone = $data["phone"];
        $start = ($page - 1) * $size;

        $con = con();
        $sql = "select * from `user` where status=1 and is_delete=1 ";
        if (!empty($name)) {
            $sql .= " and name like '%$name%'";
        }
        if (!empty($phone)) {
            $sql .= " and phone like '%$phone%'";
        }
        $user = mysqli_query($con, $sql . " order by `id` DESC limit $start,$size");
        $user = mysqli_fetch_all($user, true);
        $total = mysqli_query($con, $sql);
        $total = mysqli_num_rows($total);

//        $user=mysqli_query($con,"select * from `user` ");
//        $user=mysqli_fetch_all($user,true);

        if(!empty($user)){
            $user_ids=array_column($user, 'id');
            $user_ids=implode(',', $user_ids);
            $power=mysqli_query($con,"select * from user_power_config where user_id in ($user_ids) and is_delete=1 and status=1 and check_status=1");
            $power = mysqli_fetch_all($power, true);
        }

        mysqli_close($con);

        for ($i = 0; $i < count($user); $i++) {
            $user[$i]["money"]=sprintf('%.2f',$user[$i]["money"]/100);
            switch ($user[$i]['sex']) {
                case 1:
                    $user[$i]['sex'] = '男';
                    break;
                case 2:
                    $user[$i]['sex'] = '女';
                    break;
                default:
                    $user[$i]['sex'] = '';
                    break;
            }
            if (empty($user[$i]['avatar'])) {
                $user[$i]['avatar'] = [];
            } else {
                $user[$i]['avatar'] = [$user[$i]['avatar']];
            }
            $user[$i]['nickname'] = urldecode($user[$i]['nickname']);

            $user[$i]['power'] = [];
            $user[$i]['has_vip']=false;

            for($o=0; $o<count($power); $o++){
                if($user[$i]['id']===$power[$o]['user_id']){
                    switch ($power[$o]['type']) {//类型（1：骑手，2：任务发布人，3：任务接受人，4：任务验证人，5：会员，6：后台管理员，7：超级会员）
                        case 1://
                            $power[$o]['type_text']='骑手';
                            break;
                        case 2://
                            $power[$o]['type_text']='任务发布人';
                            break;
                        case 3://
                            $power[$o]['type_text']='任务接收人';
                            break;
                        case 4://
                            $power[$o]['type_text']='任务验证人';
                            break;
                        case 5://
                            $power[$o]['type_text']='普通会员';
                            $user[$i]['has_vip']=true;
                            break;
                        case 6://
                            $power[$o]['type_text']='后台管理员';
                            break;
                        case 7://
                            $power[$o]['type_text']='超级会员';
                            break;
                    }
                    $user[$i]['power'][]=$power[$o];
                }
            }

        }



        return out_right([
            'data' => $user,
            'page' => $page,
            'size' => $size,
            'total' => $total,
            'total_page' => ceil($total / $size)
        ]);

    }

    //获取用户能力分页列表
    public function getUserPowerList($data)
    {
        $page = (int)$data['page'];
        $size = (int)$data['size'];
        $type = (int)$data['type'];//类型（1：骑手，2：任务发布人，3：任务处理人，4：任务验证人，5：会员，6：后台管理员，7：超级会员）
        $name = $data['name'];
        $phone = $data['phone'];

        $start = ($page - 1) * $size;

        $sql = "select a.*,b.openid,b.name,b.phone,b.nickname,b.avatar,b.sex,b.money,b.org,b.id as user_id,IFNULL(c.`name`,'') as account,IFNULL(c.`password`,'') AS `password` from user_power_config a  left JOIN user b on(a.user_id=b.id) left  JOIN account c on (a.user_id=c.user_id and c.is_delete=1 and c.status=1) where a.status=1 and a.is_delete=1 and a.type=$type ";

        $limit = " order by create_time DESC limit $start,$size";
        if (!empty($name)) {
            $sql .= " and b.name like '%$name%'";
        }
        if (!empty($phone)) {
            $sql .= " and b.phone like '%$phone%'";
        }
        $con = con();
        $data = mysqli_query($con, $sql . $limit);
        $data = mysqli_fetch_all($data, true);
        $total = mysqli_query($con, $sql);
        $total = mysqli_num_rows($total);

        //获取全量用户列表（过滤相关能力）
        $power = mysqli_query($con, "select * from user_power_config where is_delete=1 and type=$type ");
        $power = mysqli_fetch_all($power, true);
        $user_ids = implode(',', array_column($power, 'user_id'));
        if (empty($user_ids)) {
            $user_ids = "where not ( (`name` is null or `name`='' ) and phone=0 )";
        } else {
            $user_ids = "where (not ( (`name` is null or `name`='' ) and phone=0 ) ) and a.id not in ($user_ids)";
        }

        $user = mysqli_query($con, "select a.id as id, CONCAT(IFNULL(a.name,''),'(',a.phone,')') as `name`,a.phone  from user a $user_ids");
        $user = mysqli_fetch_all($user, true);

        mysqli_close($con);

        for ($i = 0; $i < count($data); $i++) {
            $data[$i]['money']=sprintf("%.2f",$data[$i]['money']/100);
            switch ($data[$i]['type']) {//类型（1：骑手，2：任务发布人，3：任务接受人，4：任务验证人，5：会员，6：后台管理员）
                case 1:
                    $data[$i]['type_text'] = '配送员';
                    break;
                case 2:
                    $data[$i]['type_text'] = '任务发布人';
                    break;
                case 3:
                    $data[$i]['type_text'] = '任务处理人';
                    break;
                case 4:
                    $data[$i]['type_text'] = '任务验证人';
                    break;
                case 5:
                    $data[$i]['type_text'] = '会员';
                    break;
                case 6:
                    $data[$i]['type_text'] = '后台管理员';
                    break;
                case 7:
                    $data[$i]['type_text'] = '超级会员';
                    break;
                default:
                    break;
            }
            if ($data[$i]['sex'] == 1) {
                $data[$i]['sex'] = '男';
            } else {
                $data[$i]['sex'] = '女';
            }
            $data[$i]['create_time'] = date('Y-m-d H:i:s', $data[$i]['create_time']);
            $data[$i]['update_time'] = date('Y-m-d H:i:s', $data[$i]['update_time']);
            switch ((int)$data[$i]['check_status']) {
                case 0://待审核（会员）
                    $data[$i]['check_status_text'] = '待审核';
                    break;
                case 1://审核通过（会员）
                    $data[$i]['check_status_text'] = '审核通过';
                    break;
                case 2://审核驳回（会员）
                    $data[$i]['check_status_text'] = '审核驳回';
                    break;
                default:
                    $data[$i]['check_status_text'] = '未定义';
                    break;
            }
        }

        return out_right([
            'data' => $data,
            'page' => $page,
            'size' => $size,
            'total' => $total,
            'total_page' => ceil($total / $size),
            'user' => $user

        ]);

    }

    //获取全量用户列表(过滤相关能力)
    public function getAllForType($data)
    {
        $type = (int)$data['type'];

        $con = con();
        $power = mysqli_query($con, "select * from user_power_config where is_delete=1 and type=$type ");
        $power = mysqli_fetch_all($power, true);
        $user_ids = implode(',', array_column($power, 'user_id'));
        if (empty($user_ids)) {
            $user_ids = '';
        } else {
            $user_ids = " where a.id not in ($user_ids)";
        }

        $user = mysqli_query($con, "select a.id as id, CONCAT(a.name,'(',a.phone,')') as `name`  from user a $user_ids");
        $user = mysqli_fetch_all($user, true);
        mysqli_close($con);

        return out_right($user);
    }

    //添加人员赋能
    public function addUserPower($data)
    {
        $type = (int)$data['type'];
        $user_id = $data['user_id'];
        $remark = $data['remark'];
        $account = $data['account'];
        $password = $data['password'];
        if ($type === 6) {
            $user_id = [$user_id];
        }

        $con = con();
        $time = time();
        if ($type === 6) {
            $res = mysqli_query($con, "select * from account where `name`='$account' and is_delete=1");
            $res = mysqli_num_rows($res);
            if ($res > 0) {
                mysqli_close($con);
                return out_error('存在重复账号名！请重新输入！');
            }
        }
        for ($i = 0; $i < count($user_id); $i++) {
            $id = (int)$user_id[$i];
            $res = mysqli_query($con, "insert into user_power_config(user_id,type,create_time,update_time,remark) values($id,$type,$time,$time,'$remark')");
            if ($res) {
                switch ($type) {
                    case 5://会员
                        $res = mysqli_query($con, "update user set is_vip=1,update_time=$time where id=$id");
                        break;
                    case 7://超级会员
                        $res = mysqli_query($con, "update user set is_vip=1,update_time=$time where id=$id");
                        break;
                    case 6://后台管理员
                        mysqli_query($con, "insert into account(user_id,name,password,create_time,update_time) values($id,'$account','$password',$time,$time)");
                        break;
                    default:
                        break;
                }
            }
        }
        mysqli_close($con);
        return out_right();
    }

    //修改赋能人员的状态
    public function changePowerStatus($data)
    {
        $id = (int)$data['id'];
        $user_id = (int)$data['user_id'];
        $status = (int)$data['status'];
        $type = (int)$data['type'];

        $con = con();
        $time = time();
        $res = mysqli_query($con, "update user_power_config set status=$status,update_time=$time where id=$id and is_delete=1");
        if ($res) {
            switch ($type) {
                case 5://会员
                    $res = mysqli_query($con, "update user set is_vip=$status,update_time=$time where id=$user_id");
                    break;
                case 7://超级会员
                    $res = mysqli_query($con, "update user set is_vip=$status,update_time=$time where id=$user_id");
                    break;
                case 6://后台管理员
                    $res = mysqli_query($con, "update account set status=$status,update_time=$time where user_id=$user_id");
                    break;
                default:
                    break;
            }
        }

        mysqli_close($con);
        if ($res) {
            return out_right();
        } else {
            return out_error();
        }

    }

    //删除赋能人员
    public function delUserPower($data)
    {
        $id = (int)$data['id'];
        $user_id = (int)$data['user_id'];
        $type = (int)$data['type'];
        $con = con();
        $time = time();
        $res = mysqli_query($con, "update user_power_config set is_delete=0,delete_time=$time where id=$id and is_delete=1");
        if ($res) {
            switch ($type) {
                case 5://会员
                    $res = mysqli_query($con, "update user set is_vip=0,update_time=$time where id=$user_id");
                    break;
                case 7://超级会员
                    $res = mysqli_query($con, "update user set is_vip=0,update_time=$time where id=$user_id");
                    break;
                case 6://后台管理员
                    $res = mysqli_query($con, "update account set is_delete=0,delete_time=$time where user_id=$user_id");
                    break;
                default:
                    break;
            }
        }
        mysqli_close($con);
        if ($res) {
            return out_right();
        } else {
            return out_error();
        }
    }

    //编辑用户
    public function edit($data)
    {
        $id = (int)$data['id'];
        $name = $data['name'];
        $phone = (int)$data['phone'];
        $org = $data['org'];
        $money = $data['money']*100;
        if(isset($data['remark'])){
            $remark = $data['remark'];
            $remark=",remark='$remark'";
        }else{
            $remark = '';
        }
        $time = time();
        $con = con();
        $res = mysqli_query($con, "update user set name='$name',money=$money,phone=$phone,org='$org'$remark,update_time=$time where id=$id");
        mysqli_close($con);
        if ($res) {
            return out_right();
        } else {
            return out_error();
        }

    }

    //会员审核
    public function checkVip($data)
    {
        $id = (int)$data['id'];
        $type = (int)$data['type'];
        $time = time();
        $con = con();
        $res = mysqli_query($con, "update user_power_config set check_status=$type,update_time=$time where id=$id");
        mysqli_close($con);
        if ($res) {
            return out_right();
        } else {
            return out_error();
        }

    }

    //超级会员表格导入
    public function exportSuperVip($data)
    {
        $time=time();
        $img = $data['file'];
        $file = base64_to_file::getAll("", $img[0]["file_name"], $img[0]["file"], $img[0]['size']);

        $data=readXlsxFile($file['path']);
        array_shift($data);
        $phones=array_column($data,1);
        $phones=implode(",",$phones);



        $con=con();
        $user=mysqli_query($con,"select * from user where phone in ($phones)");
        $user=mysqli_fetch_all($user,true);

        $add=[];
        $update=[];
        for($i=0;$i<count($data);$i++){
            $has=false;
            $user_id=0;
            for($o=0;$o<count($user);$o++){
                if($data[$i][1]===$user[$o]['phone']){
                    $has=true;
                    $user_id=(int)$user[$o]['id'];
                }
            }
            if($has){//存在，则加入到修改
                $a=$data[$i];
                $a[2]=$user_id;
                $update[]=$a;
            }else{//不存在，则加入到添加
                $add[]=$data[$i];
            }
        }
        //修改阶段
        if(!empty($update)){
            $user_ids=array_column($update,2);
            $user_ids=implode(",",$user_ids);
            $power=mysqli_query($con,"select * from user_power_config where user_id in ($user_ids) and type=7 and is_delete=1 ");
            $power=mysqli_fetch_all($power,true);
            for($i=0;$i<count($update);$i++){
                $user_id=(int)$update[$i][2];
                $has=false;
                $name=$update[$i][0];
                $phone=(int)$update[$i][1];
                mysqli_query($con,"update user set name='$name',update_time=$time where phone=$phone");
                for($o=0;$o<count($power);$o++){
                    if((int)$power[$o]['user_id']===$user_id){
                        $has=true;
                    }
                }
                if(!$has){
                    mysqli_query($con,"insert into user_power_config(user_id,type,create_time,update_time,remark) values($user_id,7,$time,$time,'超级会员导入自动添加')");
                }
            }
        }
        //新增阶段
        for($i=0;$i<count($add);$i++){
            $name=$add[$i][0];
            $phone=(int)$add[$i][1];
            mysqli_query($con,"insert into user(nickname,avatar,name,phone,is_vip,create_time,update_time,remark) values('超级会员','https://luopingcn.oss-cn-chengdu.aliyuncs.com/goods/1/avatar.png','$name',$phone,1,$time,$time,'超级会员导入自动添加')");
            $user_id=(int)mysqli_insert_id($con);
            mysqli_query($con,"insert into user_power_config(user_id,type,create_time,update_time,remark) values($user_id,7,$time,$time,'超级会员导入自动添加')");
        }
        mysqli_close($con);

        return out_right();
    }







}